package com.iteaj.iot.client.codec;

import com.iteaj.iot.client.protocol.ClientInitiativeProtocol;
import com.iteaj.network.ProtocolException;
import com.iteaj.network.client.ClientComponent;
import com.iteaj.network.message.UnParseBodyMessage;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.util.List;

public class ClientProtocolEncoder extends MessageToMessageEncoder<ClientInitiativeProtocol> {

    private ClientComponent clientComponent;

    public ClientProtocolEncoder(ClientComponent clientComponent) {
        this.clientComponent = clientComponent;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, ClientInitiativeProtocol protocol, List<Object> out) throws Exception {
        if(protocol.isRelation()) {
            if(protocol.relationKey() == null) {
                throw new ProtocolException("不存在关联Key");
            }

            clientComponent.protocolFactory().add(protocol.relationKey(), protocol, protocol.getTimeout());
        }

        // Udp协议直接写出
        if(!protocol.isTcpClient()) {
            out.add(((ClientInitiativeProtocol<?>) protocol).getPacket());
        } else { // Tcp报文
            // 构建实体报文到二进制报文
            UnParseBodyMessage message = protocol.requestMessage().build();
            out.add(Unpooled.wrappedBuffer(message.getMessage()));
        }
    }
}
